package com.lzp.exception;

import com.lzp.utils.JSONResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 异常封装输出类
 * @author: lzp
 * @createTime: 2021-08-01 21:38
 **/
@ControllerAdvice
public class ExceptionErrorHandler {

    /**
     * 异常跳转页面
     */
    public static final String ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest request,
                               HttpServletResponse response,
                               Exception e) throws Exception {

        // 后台打印日志
        e.printStackTrace();

        if (isAjax(request)) {
            // 返回ajax响应
            return JSONResult.errorException(e.getMessage());
        } else {
            // 返回页面
            ModelAndView mav = new ModelAndView();
            mav.addObject("exception", e);
            mav.addObject("url", request.getRequestURL());
            // 把错误页面返回给前端，而不是使用springboot自带的页面
            mav.setViewName(ERROR_VIEW);
            return mav;
        }
    }

    /**
     * 判断请求是否是ajax请求
     *
     * @param httpRequest
     * @return
     */
    public static boolean isAjax(HttpServletRequest httpRequest) {
        return (httpRequest.getHeader("X-Requested-With") != null
                && "XMLHttpRequest"
                .equals(httpRequest.getHeader("X-Requested-With").toString()));
    }

}